﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OptixDotNet;
using RayDen.Library.Core.Components;
using RayDen.RayEngine.Core.Devices;
using RayDen.RayEngine.Core.Threads;
using RayDen.RayEngine.IntersectionEngines.Optix;
using RayDen.RayEngine.Managers;

namespace RayDen.RayEngine.Corrector.Managers
{
    public class DeviceManager : Singleton<DeviceManager>, IDisposable
    {
        public IntersectionEngine IntersectionDevice;
        private bool lowLatency;
        private RayEngineScene scene;
        public CorrectorRenderThread[] RenderThreads;

        public DeviceManager(){}

        public void Init(bool lowLatency, RayEngineScene scn)
        {
            this.lowLatency = lowLatency;
            this.scene = scn;

            this.IntersectionDevice =
                //new MCOpenClIntersectionDevice(scene, true, 0);
                //new DadeCudaIntersectionDevice(scene, null);
                new OptixIntersectionDevice(scene, lowLatency);
            //new OptixPrimeIntersectionDevice(scene, lowLatency);
        }

        public void Start()
        {
            foreach (var renderThread in RenderThreads)
            {
                renderThread.Start();
            }
        }

        public void Stop()
        {
            foreach (var renderThread in RenderThreads)
            {
                renderThread.Stop();
            }
        }
        public void Interrupt()
        {
            foreach (var renderThread in RenderThreads)
            {
                renderThread.Stop();
            }

            if (IntersectionDevice.IsRunning)
            {
                IntersectionDevice.Stop();
            }
        }

        public void Dispose()
        {
            for (var index = 0; index < RenderThreads.Length; index++)
            {
                try
                {
                    if (RenderThreads[index] != null)
                    {
                        RenderThreads[index].Dispose();
                        RenderThreads[index] = null;

                    }
                }
                finally
                {
                    RenderThreads[index] = null;
                }
            }
            try
            {
                if (IntersectionDevice != null)
                {
                    if (IntersectionDevice.IsRunning)
                    {
                        IntersectionDevice.Stop();
                    }
                }
                else
                {
                    return;
                }
            }
            finally
            {
                if (IntersectionDevice != null)
                {
                    IntersectionDevice.Dispose();
                    IntersectionDevice = null;
                }
            }

        }
    }
}
